import React from 'react';
import { Icon, Button, Row, Col } from 'antd'
import ReactDOM from 'react-dom'
import 'styles/components/template/main-init-modal-manage/single-main-guide.scss'
import { messages, deepCopy } from "share/common";
import closeGuide from 'components/method/closeGuide'
import tween from "components/method/tween";
import Pointer from 'components/template/main-init-modal-manage/mask-guide/pointer';

import tip1Img from 'images/home/tip1.png';
import tip2Img from 'images/home/tip2.png';

import GuideImg from 'images/components/guide.png'

/**
 *
 * 样式和 Guide 不一样 copy 过来 修改的    陈行健原来的组件很棒！~
 *
 * 引导组件
 * 配合components/method/wrapGuide用的，单独用没用
 *
 * add: 判断引导框有没有超出可视区域再挪来挪去的真的太麻烦了 把横纵相对位置都自定义了一下，
 * 麻烦开发者加入引导的时候自己先跑一下保证不会超出可视区域 19-02-27 陈行健
 */
class SingleMainGuide extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      index: 0,    //当前index
      style: {},   //提示标签 style 就是left top 来 定位 标签在页面的位置的
      iconConfig: { //红点的 style
        type: '',
        style: {}
      }
    };
    this.guideFixedStyle = {
      display: 'none',
      width: 360
    };
    this.scrollDom = document.querySelector(".content-layout");
    this.lastStyle = {};
    this.callBackCount = 0;
  }

  componentDidMount(){
    this.setStyle();
    if(window.addEventListener) {
      window.addEventListener('resize', this.setStyle);
    } else {
      window.attachEvent('onresize', this.setStyle);
    }
  }

  componentWillUnmount() {
    if(window.addEventListener) {
      window.removeEventListener('resize', this.setStyle);
    } else {
      window.detachEvent('onresize', this.setStyle);
    }
  }

  //判断元素是否在浏览器可视区域内
  isInCurrentPage = DOMRect => {
    let innerWidth = document.body.scrollWidth || document.documentElement.scrollWidth;
    return DOMRect.top < window.innerHeight &&
      DOMRect.top >= -1 &&
      DOMRect.left < innerWidth &&
      DOMRect.left >= -1;
  };

  //获取当前滚动条高度
  getCurrentScrollTop = (scrollDom = this.scrollDom) => {
    if(scrollDom === window)
      return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
    else
      return scrollDom.scrollTop
  };

  setScrollTop = (scrollDom = this.scrollDom, val) => {
    if(scrollDom === window) {
      document.body.scrollTop = val;
      document.documentElement.scrollTop = val;
    } else {
      scrollDom.scrollTop = val;
    }
  };

  scrollToTop = (changeTop) => {
    let startTime = new Date();
    let move = () => {
      let timeStamp = new Date();
      let time = timeStamp - startTime;
      let targetVal = Math.tween.Linear(time, this.getCurrentScrollTop(), changeTop, 800);
      this.setScrollTop(this.scrollDom, targetVal);
      if(time < 800) {
        requestAnimationFrame(move);
      }
    };
    move();
  };

  setStyle = () => {
    const { index } = this.state;
    const nowGuide = this.props.actions[index];
    this.callBackCount = 0; //重置回调次数
    let dom = ReactDOM.findDOMNode(nowGuide.ref);
    let pos = dom.getBoundingClientRect(); //被引导元素的DOMRect对象
    //如果元素不在浏览器可视区域内，先调整至可视区域，然后重新获取Rect对象
    if(!this.isInCurrentPage(pos)) {
      this.props.RefreshList()
      if(pos.top > window.innerHeight){
        this.scrollToTop(pos.top - window.innerHeight);
      } else if(pos.top < 0) {
        this.scrollToTop(pos.top);
      }
      setTimeout(() => {
        this.resetPos();
      }, 801);
    } else {
      this.resetPos();
    }
  };

  resetPos = () => {
    const { index } = this.state;
    const nowGuide = this.props.actions[index];
    let dom = ReactDOM.findDOMNode(nowGuide.ref);
    let pos = dom.getBoundingClientRect(); //被引导元素的DOMRect对象
    let guide = this.guideFixedStyle; //引导提示框的宽高对象
    let gap = 20; //提示框与被引导元素之间的间距
    let style = { display: 'block' };
    let iconConfig = {
      className: '',
      style: {}
    };
    //定义 卡片位置的  通过placement 定义 卡片放在元素的那个方向
    switch(nowGuide.placement){
      case 'bottom':
        style.top = pos.top + pos.height + gap;
        iconConfig = {
          className: 'arrow-up',
          style: nowGuide.arrowStyle
        };
        break;
      case 'left':
        style.left = (pos.left - guide.width - gap) < 0 ? 0 : pos.left - guide.width - gap;
        iconConfig = {
          className: 'arrow-right',
          style: nowGuide.arrowStyle
        };
        break;
      case 'top':
        style.top = pos.top - guide.height - gap;
        iconConfig = {
          className: 'arrow-down',
          style: nowGuide.arrowStyle
        };
        break;
      case 'right':
        style.left = pos.left + pos.width + gap;
        iconConfig = {
          className: 'arrow-left',
          style: nowGuide.arrowStyle
        };
        break;
      case 'main':
        style.left = 200 + (pos.width - guide.width)/2;
        style.top = pos.top + 520
        iconConfig = {
          className: 'arrow-up',
          style: nowGuide.arrowStyle
        };
        break;
      case 'help':
        style.top = pos.top + pos.height + gap;
        style.left =  pos.right - guide.width - 90;
        iconConfig = {
          className: 'arrow-up',
          style: nowGuide.arrowStyle
        };
        break;
      case 'mine':
        style.left = pos.left - guide.width - gap - 20;
        style.top =  pos.bottom - guide.height;
        iconConfig = {
          className: 'arrow-up',
          style: nowGuide.arrowStyle
        };
        break;
    }

    //为了防止超出浏览器可视区域
    //bottom和top位置模式可以选择横向相对位置，默认为center
    if(nowGuide.placement === "bottom" || nowGuide.placement === "top")
      switch (nowGuide.inline){
        case 'start':
          style.left = pos.left;
          break;
        case 'center':
          style.left = pos.left - (guide.width - pos.width) / 2;
          break;
        case 'end':
          style.left =  pos.right - guide.width;
          break;
        default:
          style.left = pos.left - (guide.width - pos.width) / 2;
          break;
      }

    //为了防止超出浏览器可视区域
    //left和right位置模式可以选择纵向相对位置，默认为center
    if(nowGuide.placement === "left" || nowGuide.placement === "right")
      switch (nowGuide.block){
        case 'start':
          style.top = pos.top;
          break;
        case 'center':
          style.top = pos.top - (guide.height - pos.height) / 2;
          break;
        case 'end':
          style.top = pos.bottom - guide.height;
          break;
        default:
          style.top = pos.top - (guide.height - pos.height) / 2;
          break;
      }
    style.left += window.pageXOffset;
    if(nowGuide.dynamic) {
      let f = 0;
      if(style.left < 202){nowGuide.placement = "right"; f = 1; this.callBackCount++;}
      if(style.top < 0){nowGuide.placement = "bottom"; f = 1; this.callBackCount++;}
      if(style.left + guide.width > window.innerWidth){nowGuide.placement = "left"; f = 1; this.callBackCount++;}
      if(style.top + guide.height > window.innerHeight){nowGuide.placement = "top"; f = 1; this.callBackCount++;}
      if(f && this.callBackCount < 5) {this.resetPos(); return;}
    }

    if(window.ISIE9 && index) {
      tween(document.querySelector("#guide-helper-component"), this.lastStyle, style, 500);
      setTimeout(() => {
        this.setState({ style, iconConfig });
      },501)
    }else{
      this.setState({ style, iconConfig })
    }
  };

  handleOver = () => {
    this.props.onClose();
  };

  onNext = (index, isNext, isReturn) => {
    let newIndex = isNext ? index + 1 : index - 1;
    if (!isReturn) {
      this.props.onNext(newIndex);
      this.setState({ index: newIndex }, this.setStyle)
    }
  }

  render() {
    const { actions } = this.props;
    const { index, style, iconConfig } = this.state;
    const action  = actions[index];
    return (
      <div className="guide-new" style={{ ...this.guideFixedStyle, ...style }} id="guide-helper-component">
        <img src={index%2 ? tip1Img : tip2Img} onMouseDown={e=>e.preventDefault()} className='tip-bg-img' />
        <Icon className="close-icon" onClick={this.handleOver} type="close" />
        <Pointer {...iconConfig}/>
        <div className='guide-content'>
          <div className="guide-title">
            {action.title}
          </div>
          <div className="guide-tips">
            {action.content}
          </div>
          <div className="flex-bottom">
            <div className="indicator">
              <Icon
                type="left"
                className={index === 0 ? 'forbid' : ''}
                onClick={()=>{this.onNext(index, false ,index === 0)}}
              />
              {index + 1}/{actions.length}
              <Icon
                type="right"
                className={index + 1 === actions.length ? 'forbid' : ''}
                onClick={()=>{this.onNext(index, true, index + 1 === actions.length)}}
              />
            </div>
            <div>
              <Button type={index + 1 !== actions.length ? 'default' : 'primary'} onClick={()=>{
                index + 1 !== actions.length ? this.onNext(index, true) : this.handleOver()
              }}>
                {index + 1 !== actions.length ? messages('common-1.key297')/*知道了*/ : messages('common-1.key415')/*完成*/}
              </Button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

SingleMainGuide.PropTypes = {
  style: React.PropTypes.object,
  actions: React.PropTypes.array,
};

SingleMainGuide.defaultProps = {
  style: {}
};

export default SingleMainGuide;
